const {verifyToken} = require('../utils/jwt');
const UserModel = require('../models/UserModel');
const {generateAccessToken} = require('../utils/jwt');

const verifyUserToken = async (req, res, next) => {
    try {
        const token = req.headers.authorization?.split(' ')[1];
        const refreshToken = req.cookies?.refreshToken;
        // 先验证token有没有过期
        const decodedAccess = await verifyToken(token);
        // 如果token过期，则验证refreshToken
        if (!decodedAccess) {
            // 验证刷新令牌
            const decodedRefresh = await verifyToken(refreshToken);
            if(!decodedRefresh) {
                return res.status(401).json({
                    code: 402,
                    msg: 'token已过期，请重新登录',
                });
            }
            // 3. 查询用户是否存在
            const user = await UserModel.findById(decodedRefresh.id);
            if (!user) {
                return res.status(401).json({
                    message: '用户不存在请注册一个账号',
                });
            }
            const newAccessToken = generateAccessToken({
                id: user._id,
                username: user.username,
                email: user.email,
            });
            let userinfo = {
                id: user._id,
                username: user.username,
                email: user.email,
            }
            if (newAccessToken) {
                res.send({
                    code: 200,
                    msg: '验证成功',
                    data: {
                        token: newAccessToken,
                        ...userinfo
                    }
                })
            }
        } else {
            if (!refreshToken) {
                res.send({
                    code: 402,
                    msg: '没有刷新令牌请先登录,请先登录'
                })
            }else{
                // 未过期放行
                UserModel.email = decodedAccess.email;
                next();
            }
        }
    } catch (error) {
        console.log(error);
    }
}

module.exports = {
    verifyUserToken
}